const http = require('http')
const { router } = require('./router')
const ipAddr = require('./ipAddr')
const services = {};

/**
 * 启动服务
 * @param {Number} port 端口
 * @param {Function} success 启动成功回调
 */
function serviceStart(port, success) {
    const service = http.createServer((req, res) => {
        res.setHeader("Access-Control-Allow-Origin", "*");
        router(req, res, port)
    })

    service.listen(port, () => {
        services[port] = service
        const data = service.address()
        data.ipAddr = ipAddr
        success(data)
    })
}

/**
 * 关闭服务
 * @param {Number} port 端口
 */
function serviceClose(port) {
    if (services[port]) {
        services[port].close()
        delete services[port]
    }
}

/**
 * 关闭所有服务
 */
function serviceCloseAll() {
    for (const port in services) {
        serviceClose(port)
    }
}

module.exports = { serviceStart, serviceClose, serviceCloseAll }
